//  创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { LoginDTO, UserInfoVO } from '@/api/user/type'
import type { Response } from '@/api/type'
import type { UserState } from '@/store/modules/types/type'
// 引入常量路由 
import { constantRoutes } from '@/router/routers'
import { SET_TOKEN, REMOVE_TOKEN, GET_TOKEN } from '@/utils/token'

export const useUserStore = defineStore('user', {
  // 小仓库存储数据的地方    
  state: (): UserState => {
    return {
      token: GET_TOKEN(), // 用户唯一标识token
      menuRoutes: constantRoutes, // 仓库存储生成菜单需要数组（路由）
      username: '',
      avatar: ''
    }
  },
  //  异步| 逻辑的地方
  actions: {
    //  用户登录
    async userLogin(data: LoginDTO) {
      let result: Response<string> = await reqLogin(data)
      if (result.code === 200) {
        this.token = result.data
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 获取用户信息
    async userInfo() {
      let result: Response<UserInfoVO> = await reqUserInfo()
      if (result.code === 200) {
        this.username = result.data?.username;
        this.avatar = result.data?.avatar;
        return 'ok'
      }
      return Promise.reject(new Error(result.message))
    },
    async userLogout() {
      //  退出登录请求
      let result: Response<void> = await reqLogout()
      if (result.code !== 200) {
        return Promise.reject(new Error(result.message))
      }
      REMOVE_TOKEN()
      this.token = ''
      this.username = ''
      this.avatar = ''
      return 'ok'
    }

  },
  getters: {
    // 计算属性


  },
})

